package token

import (
	"context"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/msg/logmsg"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateTokenLogic {
	return &UpdateTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateTokenLogic) UpdateToken(in *backend.TokenInfo) (*backend.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	token, err := l.svcCtx.SysToken.FindOneNoCache(l.ctx, nil, *in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Status != nil {
		token.Status = uint8(*in.Status)
	}
	if in.ExpiredAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.ExpiredAt); err == nil {
			token.ExpiredAt = null.TimeFrom(localTime)
		}
	}
	token.UpdatedAt = time.Now()

	if in.Status != nil {
		if int32(*in.Status) == globalkey.StatusBanned && token.ExpiredAt.Valid {
			nowTime := time.Now().Unix()
			expiredTime := int(token.ExpiredAt.Time.Unix() - nowTime)
			if expiredTime > 0 {
				err = l.svcCtx.BizRedis.Setex("token_"+token.Token, "1", expiredTime)
				if err != nil {
					logx.Errorw(logmsg.RedisError, logx.Field("detail", err.Error()))
					return nil, errorx.NewInternalError(i18n.RedisError)
				}
			}
		} else if int32(*in.Status) == globalkey.StatusNormal {
			_, err = l.svcCtx.BizRedis.Del("token_" + token.Token)
			if err != nil {
				logx.Errorw(logmsg.RedisError, logx.Field("detail", err.Error()))
				return nil, errorx.NewInternalError(i18n.RedisError)
			}
		}
	}

	err = l.svcCtx.SysToken.Update(l.ctx, nil, token)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
